// version 0.1.1
#include <time.h>
#include <GL/glut.h>

int N = 30;
int M = 20;
int scale = 25;

int w = scale * N;
int h = scale * M;

int dir;
int num = 4;

struct
{	
	int x;
	int y;
} s[100];

class Fructs
{
	public:
		int x;
		int y;
	void newFruit()
	{
		x = rand() % N;
		y = rand() % M;
	}
	void drawFruit()
	{
		glColor3f(0.0, 0.8, 0.0);
		glRectf(x*scale, y*scale, (x+1)*scale, (y+1)*scale);
	}
} m[10];

void drawField()
{
	glColor3f(0.5, 0.1, 0.1);
	glBegin(GL_LINES);

	for (int i = 0; i < w; i += scale)
	{
		glVertex2f(i, 0);
		glVertex2f(i, h);
	}
	for (int j = 0; j < h; j += scale)
	{
		glVertex2f(0, j);
		glVertex2f(w, j);
	}
	glEnd();
}

void tick()
{
	for (int i = num; i > 0; --i)
	{
		s[i].x = s[i-1].x;
		s[i].y = s[i-1].y;
	}

	if (dir == 0) s[0].y++;
	if (dir == 1) s[0].x--;
	if (dir == 2) s[0].x++;
	if (dir == 3) s[0].y--;

	for (int i = 0; i < 10; i++)
	{
		if ((s[0].x == m[i].x) && (s[0].y == m[i].y))
				{
				num++;
				m[i].newFruit();
				}
	}

	if (s[0].x > N-1) dir = 1;
	if (s[0].x < 0) dir   = 2;
	if (s[0].y > M-1) dir = 3;
	if (s[0].y < 0) dir   = 0;

/*
	if (s[0].x > N) dir = 1; // fixed in 0.1.1
	if (s[0].x < 0) dir = 2;
	if (s[0].y > M) dir = 3;
	if (s[0].y < 0) dir = 0;

*/

	for (int i = 1; i < num; i++)
	{
		if (s[0].x == s[i].x && s[0].y == s[i].y) num = i;
	}
}

void drawSnake()
{
	glColor3f(0.8, 0.2, 0.2);

	for (int i = 0; i < num; i++)
	{
		glRectf(s[i].x * scale, s[i].y * scale, (s[i].x + 1)*scale-2, (s[i].y + 1)*scale-2);
		glColor3f(0.6, 0.4, 0.0);
	}
}

void display()
{	
	glClear(GL_COLOR_BUFFER_BIT);
	for (int i = 0; i < 10; i++) m[i].drawFruit();
	drawField();
	drawSnake();

	glFlush();
}

void timer(int x = 0)
{
	display();

	tick();
	
	glutTimerFunc(100-(num*2), timer, 0);
}

void keyboard(int key, int a, int b)
{
	switch (key) 
	{
		case 100:
			dir = 1;
			break;
		case 101:
			dir = 0;
			break;
		case 102:
			dir = 2;
			break;
		case 103:
			dir = 3;
			break;
	}
}

int main(int argc, char **argv)
{
	for (int i = 0; i < 10; i++) m[i].newFruit();

	s[0].x = 10;
	s[0].y = 10;

	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
	glutInitWindowSize(w, h);
	glutCreateWindow("Simple");
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluOrtho2D(0, w, 0, h);

	glutDisplayFunc(display);
	glutTimerFunc(50, timer, 0);	

	glutSpecialFunc(keyboard);

	glutMainLoop();
}

